package cloud.lysky.java.on.concurrent.thread;

/**
 * @author luoly
 * @describe
 * @date 2022-10-18 19:18
 **/
public class WaitDemo {
    private static Object lock = new Object();
    private static boolean flag = true;


    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    while (flag){
                        System.out.println("wait start...");
                        try {
                            //调用wait方法，线程释放锁进入等待状态
                            lock.wait();
                            System.out.println("这里的代码在唤醒之前不会被执行");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("wait end...");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (flag){
                    synchronized (lock){
                        if (flag){
                            //调用notify唤醒其它线程
                            lock.notify();
                            System.out.println("notify...");
                            flag = false;
                        }
                    }
                }
            }
        }).start();
    }
}